package au.com.langdale.gwt.server.pump;

import java.util.ArrayList;
import java.util.List;

import au.com.langdale.gwt.client.pump.Pump;
import au.com.langdale.gwt.client.remote.Batch;
import au.com.langdale.hibernate.Sessions;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The implementation of the Pump service over hibernate.
 *  
 * @author adv
 *
 */
public class PumpImpl extends RemoteServiceServlet implements Pump {

	public Batch pull(String classname, int first, int quota) {
		Sessions.begin();
		List results = Sessions.query("from " + classname, first, quota); 
		Sessions.commit();
		Batch batch = new Batch();
		batch.contents = new ArrayList(results);
		batch.first = first;
		batch.quota = quota;
		return batch;
	}

	public Batch pull(String classname, String orderby, int first, int quota) {
		Sessions.begin();
		List results = Sessions.query("from " + classname + " order by " + orderby, first, quota); 
		Sessions.commit();
		Batch batch = new Batch();
		batch.contents = new ArrayList(results);
		batch.first = first;
		batch.quota = quota;
		return batch;
	}

	public void push(ArrayList updates, ArrayList deletes) {
		Sessions.begin();
		for(int ix = 0; ix < updates.size(); ++ix)
			Sessions.merge(updates.get(ix));
		for(int ix = 0; ix < deletes.size(); ++ix)
			Sessions.delete(deletes.get(ix));
		Sessions.commit();
	}
}
